package com.newland.esp.service.goods.Impl;

import com.newland.esp.common.util.DataResult;
import com.newland.esp.common.util.DateUtil;
import com.newland.esp.common.util.FTPUtil;
import com.newland.esp.service.goods.FileUploadService;
import com.newland.esp.vo.response.goods.FileResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDateTime;

/**
 * @param
 * @author lw
 * @descripe
 * @date 2021/10/30 18:20
 * @Version 1.0
 **/
@Service
@PropertySource(value = "classpath*:application.yml", ignoreResourceNotFound = true)
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${ftp.host}")
    String host;
    @Value("${ftp.port}")
    String port;
    @Value("${ftp.username}")
    String username;
    @Value("${ftp.password}")
    String password;
    @Value("${ftp.path}")
    String path;

    @Override
    public DataResult fileUpload(String originalFilename, InputStream inputStream) {
        //得到日期格式
        String datePath = DateUtil.getDateStr(LocalDateTime.now(), DateUtil.pattern_date);
        // 得到文件上传至服务器中的名称
        String remoteName = FTPUtil.fileUpload(host, Integer.parseInt(port), username, password, originalFilename, inputStream, path + datePath);

        if (remoteName != null && remoteName.length() > 0) {
            // 最终上传至服务器的文件全路径：http://192.168.177.100/2019/02/25/UUID.jpg
            String imageUrl = "http://"+host+"/"+datePath+"/"+remoteName;
            FileResult result = new FileResult();
            result.setTmp_path("tmp_uploads/"+remoteName);
            result.setUrl(imageUrl);
            return DataResult.success("文件上传成功！",result);
        }
        return DataResult.error();
    }

    /**
     * 删除ftp服务器文件
     *
     * @param pathName
     * @return
     */
    @Override
    public boolean fileDelete(String pathName) {
        return FTPUtil.fileDelete(host, Integer.parseInt(port), username, password, pathName, path);
    }
}
